<template>
  <view class="music-player">
    <!-- 头部返回按钮 -->
    <view class="header">
      <view class="back-btn" @click="navigateBack">
        <text class="fa fa-arrow-left"></text>
      </view>
      <view class="song-info">
        <text class="song-name">{{ musicInfo.name }}</text>
        <text class="artist-name">{{ musicInfo.artists }}</text>
      </view>
      <view class="like-btn" @click="toggleLike">
        <text class="fa" :class="isLiked ? 'fa-heart' : 'fa-heart-o'"></text>
      </view>
    </view>

    <!-- 专辑封面 -->
    <view class="album-container">
      <view class="album-cover" :style="{ transform: `rotate(${rotateDegree}deg)` }">
        <image :src="musicInfo.coverImgUrl" mode="aspectFill" alt="专辑封面"></image>
      </view>
    </view>

    <!-- 歌词区域 -->
    <view class="lyric-container">
      <scroll-view class="lyric-scroll" scroll-y="true" :scroll-top="lyricScrollTop" @scroll="onLyricScroll">
        <view class="lyric-content">
          <view v-for="(line, index) in lyricLines" :key="index" 
                :class="{'current-lyric': currentLineIndex === index}"
                class="lyric-line">
            {{ line.text }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部歌词提示 -->
    <view class="bottom-lyric" v-if="showBottomLyric">
      <text>{{ currentLyric }}</text>
    </view>

    <!-- 进度条 -->
    <view class="progress-container">
      <text class="current-time">{{ formatTime(currentTime) }}</text>
      <slider class="progress-slider" :value="currentTime" :max="duration" 
              @changing="onProgressChanging" @change="onProgressChange"></slider>
      <text class="total-time">{{ formatTime(duration) }}</text>
    </view>

    <!-- 控制按钮 -->
    <view class="control-container">
      <view class="play-mode" @click="changePlayMode">
        <text class="fa" :class="playModeIcon"></text>
      </view>
      <view class="prev-btn" @click="playPrev">
        <text class="fa fa-step-backward"></text>
      </view>
      <view class="play-btn" @click="togglePlay">
        <text class="fa" :class="isPlaying ? 'fa-pause' : 'fa-play'"></text>
      </view>
      <view class="next-btn" @click="playNext">
        <text class="fa fa-step-forward"></text>
      </view>
      <view class="playlist-btn" @click="togglePlaylistVisible">
        <text class="fa fa-list"></text>
      </view>
    </view>

    <!-- 播放列表模态框 -->
    <view class="playlist-modal" v-if="isPlaylistVisible">
      <view class="modal-mask" @click="togglePlaylistVisible"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">播放列表</text>
          <text class="modal-close" @click="togglePlaylistVisible">×</text>
        </view>
        <view class="modal-body">
          <view 
            class="playlist-item" 
            v-for="(item, index) in playlist" 
            :key="item.id"
            :class="{'active': index === currentIndex}"
            @click="playFromPlaylist(index)"
          >
            <text>{{ item.name }}</text>
            <text>{{ item.artists }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { songDetail, songUrl, songLyric } from '@/common/api.js';

export default {
  data() {
    return {
      // 音乐信息
      musicInfo: {
        name: '孤勇者',
        artists: '陈奕迅',
        coverImgUrl: 'https://picsum.photos/400/400?random=1',
        url: ''
      },

      // 播放状态
      isPlaying: false,
      currentTime: 0,
      duration: 240, // 秒
      playMode: 0, // 0:顺序播放 1:单曲循环 2:随机播放

      // 歌词相关
      lyricLines: [
        { time: 0, text: '前奏' },
        { time: 10, text: '都 是勇敢的' },
        { time: 14, text: '你额头的伤口 你的 不同 你犯的错' },
        { time: 20, text: '都 不必隐藏' },
        { time: 24, text: '你破旧的玩偶 你的 面具 你的自我' },
        { time: 30, text: '他们说 要带着光 驯服每一头怪兽' },
        { time: 36, text: '他们说 要缝好你的伤 没有人爱小丑' },
        { time: 42, text: '为何孤独 不可 光荣' },
        { time: 45, text: '人只有不完美 值得歌颂' },
        { time: 50, text: '谁说污泥满身的不算英雄' }
      ],
      currentLineIndex: 0,
      currentLyric: '前奏',
      lyricScrollTop: 0,
      showBottomLyric: false,

      // 动画相关
      rotateDegree: 0,
      rotateTimer: null,
      timer: null,

      // 收藏状态
      isLiked: false,

      // 模拟播放列表
      playlist: [
        { id: 1, name: '孤勇者', artists: '陈奕迅', coverImgUrl: 'https://picsum.photos/400/400?random=1' },
        { id: 2, name: '海阔天空', artists: 'Beyond', coverImgUrl: 'https://picsum.photos/400/400?random=2' },
        { id: 3, name: '青花瓷', artists: '周杰伦', coverImgUrl: 'https://picsum.photos/400/400?random=3' },
        { id: 4, name: '稻香', artists: '周杰伦', coverImgUrl: 'https://picsum.photos/400/400?random=4' },
        { id: 5, name: '平凡之路', artists: '朴树', coverImgUrl: 'https://picsum.photos/400/400?random=5' }
      ],

      // 当前播放歌曲在列表中的索引
      currentIndex: 0,

      // 播放列表模态框显示状态
      isPlaylistVisible: false
    };
  },
  computed: {
    // 播放模式图标
    playModeIcon() {
      switch(this.playMode) {
        case 0: return 'fa-list';
        case 1: return 'fa-repeat';
        case 2: return 'fa-random';
        default: return 'fa-list';
      }
    }
  },
  methods: {
    // 格式化时间为 MM:SS 格式
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },

    // 切换播放状态
    togglePlay() {
      this.isPlaying = !this.isPlaying;

      if (this.isPlaying) {
        this.startTimer();
        this.startRotate();
        // 实际项目中这里应该调用API开始播放音乐
        console.log('开始播放音乐');
      } else {
        this.stopTimer();
        this.stopRotate();
        // 实际项目中这里应该调用API暂停音乐
        console.log('暂停播放音乐');
      }
    },

    // 开始旋转专辑封面
    startRotate() {
      this.stopRotate();
      this.rotateTimer = setInterval(() => {
        this.rotateDegree += 1;
        if (this.rotateDegree >= 360) {
          this.rotateDegree = 0;
        }
      }, 50);
    },

    // 停止旋转专辑封面
    stopRotate() {
      if (this.rotateTimer) {
        clearInterval(this.rotateTimer);
        this.rotateTimer = null;
      }
    },

    // 停止计时器
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    // 解析歌词
    parseLyric(lyric) {
      const lines = lyric.split('\n');
      const lyricLines = [];
      lines.forEach(line => {
        const timeReg = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;
        const timeResult = line.match(timeReg);
        if (timeResult) {
          const minutes = parseInt(timeResult[1], 10);
          const seconds = parseInt(timeResult[2], 10);
          const milliseconds = parseInt(timeResult[3], 10);
          const time = minutes * 60 + seconds + milliseconds / 1000;
          const text = line.replace(timeReg, '').trim();
          if (text) {
            lyricLines.push({ time, text });
          }
        }
      });
      return lyricLines;
    },

    // 更新歌词
    updateLyric() {
      for (let i = this.lyricLines.length - 1; i >= 0; i--) {
        if (this.currentTime >= this.lyricLines[i].time) {
          if (this.currentLineIndex !== i) {
            this.currentLineIndex = i;
            this.currentLyric = this.lyricLines[i].text;

            // 滚动歌词
            if (i > 2) {
              this.lyricScrollTop = (i - 2) * 40; // 每行歌词高度约40px
            }
          }
          break;
        }
      }
    },

    // 进度条改变中
    onProgressChanging(e) {
      this.currentTime = e.detail.value;
      this.updateLyric();
    },

    // 进度条改变完成
    onProgressChange(e) {
      this.currentTime = e.detail.value;
      this.updateLyric();

      // 如果暂停状态，拖动后播放
      if (!this.isPlaying) {
        this.togglePlay();
      }
    },

    // 歌词滚动事件
    onLyricScroll(e) {
      // 歌词区域滚动时隐藏底部歌词提示
      this.showBottomLyric = e.detail.scrollTop < 10;
    },

    // 开始计时器
    startTimer() {
      this.stopTimer();
      this.timer = setInterval(() => {
        if (this.currentTime < this.duration) {
          this.currentTime += 1;
          this.updateLyric();
        } else {
          // 播放结束，根据播放模式处理
          if (this.playMode === 1) {
            // 单曲循环
            this.currentTime = 0;
          } else {
            // 播放下一首
            this.playNext();
          }
        }
      }, 1000);
    },

    // 改变播放模式
    changePlayMode() {
      this.playMode = (this.playMode + 1) % 3;
      // 实际项目中这里应该保存播放模式到本地存储
      console.log(`播放模式已切换为: ${['顺序播放', '单曲循环', '随机播放'][this.playMode]}`);
    },

    // 播放上一首
    playPrev() {
      if (this.playlist.length <= 1) return;

      this.stopTimer();
      this.stopRotate();

      if (this.playMode === 2) {
        // 随机播放模式
        this.currentIndex = Math.floor(Math.random() * this.playlist.length);
      } else {
        // 顺序播放模式
        this.currentIndex = (this.currentIndex - 1 + this.playlist.length) % this.playlist.length;
      }

      this.loadMusic(this.playlist[this.currentIndex]);
      this.isPlaying = true;
      this.startTimer();
      this.startRotate();
    },

    // 播放下一首
    playNext() {
      if (this.playlist.length <= 1) return;

      this.stopTimer();
      this.stopRotate();

      if (this.playMode === 2) {
        // 随机播放模式
        this.currentIndex = Math.floor(Math.random() * this.playlist.length);
      } else {
        // 顺序播放模式
        this.currentIndex = (this.currentIndex + 1) % this.playlist.length;
      }

      this.loadMusic(this.playlist[this.currentIndex]);
      this.isPlaying = true;
      this.startTimer();
      this.startRotate();
    },

    // 加载音乐
    async loadMusic(music) {
      this.musicInfo = { ...music, url: '' };
      this.currentTime = 0;
      this.currentLineIndex = 0;
      this.currentLyric = this.lyricLines[0].text || '';
      this.lyricScrollTop = 0;

      try {
        // 获取歌曲详情
        const detailRes = await songDetail(music.id);
        const validDetailRes = detailRes[1]?.data;
        if (!validDetailRes || validDetailRes.code !== 200) {
          throw new Error(validDetailRes?.msg || '获取歌曲详情失败');
        }
        this.duration = validDetailRes.songs[0].dt / 1000; // 转换为秒

        // 获取歌曲播放地址
        const urlRes = await songUrl(music.id);
        const validUrlRes = urlRes[1]?.data;
        if (!validUrlRes || validUrlRes.code !== 200) {
          throw new Error(validUrlRes?.msg || '获取歌曲播放地址失败');
        }
        this.musicInfo.url = validUrlRes.data[0].url;

        // 获取歌词
        const lyricRes = await songLyric(music.id);
        const validLyricRes = lyricRes[1]?.data;
        if (!validLyricRes || validLyricRes.code !== 200) {
          throw new Error(validLyricRes?.msg || '获取歌词失败');
        }
        this.lyricLines = this.parseLyric(validLyricRes.lrc.lyric);
      } catch (error) {
        console.error('加载音乐失败:', error);
        uni.showToast({
          title: '加载音乐失败',
          icon: 'none'
        });
      }
    },

    // 切换收藏状态
    toggleLike() {
      this.isLiked = !this.isLiked;
      // 实际项目中这里应该调用API更新收藏状态
      console.log(`歌曲收藏状态已切换为: ${this.isLiked ? '已收藏' : '未收藏'}`);
    },

    // 返回上一页
    navigateBack() {
      uni.navigateBack({
        delta: 1
      });
    },

    // 显示/隐藏播放列表模态框
    togglePlaylistVisible() {
      this.isPlaylistVisible = !this.isPlaylistVisible;
    },

    // 从播放列表中播放歌曲
    playFromPlaylist(index) {
      this.currentIndex = index;
      this.loadMusic(this.playlist[index]);
      this.isPlaying = true;
      this.startTimer();
      this.startRotate();
      this.togglePlaylistVisible();
    }
  },
  onLoad(options) {
    // 接收传递过来的歌曲信息
    if (options.id) {
      this.musicInfo.id = options.id;
      this.musicInfo.name = decodeURIComponent(options.name);
      this.musicInfo.artists = decodeURIComponent(options.artists);
      this.musicInfo.coverImgUrl = decodeURIComponent(options.coverImgUrl);

      // 查找当前歌曲在播放列表中的索引
      const index = this.playlist.findIndex(item => item.id == options.id);
      if (index !== -1) {
        this.currentIndex = index;
      }

      // 实际项目中这里应该从API获取音乐信息和歌词
      this.loadMusic(this.musicInfo);
    }
  },
  onShow() {
    // 页面显示
    if (this.isPlaying) {
      this.startTimer();
      this.startRotate();
    }
  },
  onHide() {
    // 页面隐藏
    this.stopRotate();
    this.stopTimer();
  },
  onUnload() {
    // 页面卸载
    this.stopRotate();
    this.stopTimer();
  }
};
</script>

<style>
/* 引入Font Awesome CDN */
@import url("https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css");

/* 整体样式 */
.music-player {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 100rpx;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 10;
}

.back-btn, .like-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #333;
}

.song-info {
  flex: 1;
  text-align: center;
  margin: 0 20rpx;
}

.song-name {
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.artist-name {
  font-size: 26rpx;
  color: #666;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 专辑封面样式 */
.album-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.album-cover {
  width: 500rpx;
  height: 500rpx;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 0 40rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: transform 0.3s ease;
}

.album-cover image {
  width: 440rpx;
  height: 440rpx;
  border-radius: 50%;
  object-fit: cover;
}

/* 歌词区域样式 */
.lyric-container {
  flex: 1;
  margin: 0 30rpx;
  border-radius: 20rpx;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  position: relative;
}

.lyric-scroll {
  height: 100%;
}

.lyric-content {
  padding: 30rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.lyric-line {
  padding: 10rpx 0;
  font-size: 28rpx;
  color: #666;
  text-align: center;
  width: 100%;
  transition: all 0.3s ease;
}

.current-lyric {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  transform: scale(1.05);
}

.bottom-lyric {
  position: absolute;
  bottom: 220rpx;
  left: 0;
  right: 0;
  text-align: center;
  padding: 10rpx 0;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(10rpx);
  z-index: 5;
}

.bottom-lyric text {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

/* 进度条样式 */
.progress-container {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
}

.current-time, .total-time {
  width: 100rpx;
  text-align: center;
  font-size: 24rpx;
  color: #666;
}

.progress-slider {
  flex: 1;
  margin: 0 20rpx;
}

/* 控制按钮样式 */
.control-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 30rpx 0 60rpx 0;
}

.control-container view {
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-mode, .playlist-btn {
  width: 80rpx;
  height: 80rpx;
  font-size: 32rpx;
  color: #666;
}

.prev-btn, .next-btn {
  width: 90rpx;
  height: 90rpx;
  font-size: 36rpx;
  color: #333;
}

.play-btn {
  width: 120rpx;
  height: 120rpx;
  background-color: #333;
  border-radius: 50%;
  font-size: 48rpx;
  color: #fff;
  box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.2);
}

/* 播放列表模态框样式 */
.playlist-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 20;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 20rpx;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.modal-close {
  font-size: 36rpx;
  color: #666;
}

.modal-body {
  max-height: 500rpx;
  overflow-y: auto;
  padding-top: 20rpx;
}

.playlist-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.playlist-item.active text {
  color: #d43c33;
}
</style>